package com.ebupt.migu.music.propagate.job;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;
import java.util.UUID;

public class RedisDistributedLock {

    private final Jedis jedis;
    private String lockKey;
    private String lockValue;





    public RedisDistributedLock(Jedis jedis, String lockKey) {
        this.jedis = jedis;
        this.lockKey = lockKey;
    }

    public boolean acquireLock(long timeout, long expire) {
        lockValue = UUID.randomUUID().toString();
        long startTime = System.currentTimeMillis();

        SetParams params = SetParams.setParams().nx().px(expire);

        while ((System.currentTimeMillis() - startTime) < timeout) {
            String result = jedis.set(lockKey, lockValue, params);
            if ("OK".equals(result)) {
                return true;
            }
            try {
                Thread.sleep(10); // 等待一段时间重试
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return false;
    }

    public boolean releaseLock() {
        String luaScript =
                "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                        "return redis.call('del', KEYS[1]) " +
                        "else " +
                        "return 0 " +
                        "end";
        Object result = jedis.eval(luaScript, 1, lockKey, lockValue);
        return "1".equals(result.toString());
    }

    public static void main(String[] args) {
        String redisHost = "localhost";
        int redisPort = 6379;
        Jedis jedis = new Jedis(redisHost, redisPort);

        String lockKey = "my_lock";
        RedisDistributedLock lock = new RedisDistributedLock(jedis, lockKey);

        try {
            if (lock.acquireLock(5000, 10000)) { // 等待最多5秒，锁的过期时间为10秒
                System.out.println("Lock acquired. Performing protected operation...");
                // 在这里执行需要互斥访问的操作
            } else {
                System.out.println("Failed to acquire lock.");
            }
        } finally {
            lock.releaseLock();
            System.out.println("Lock released.");
        }

        jedis.close();
    }
}